<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <!-- 左侧显示总记录数 -->
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >excel导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >excel导出</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click="showDialog = true"
            :disabled="!checkPermission('POINT-USER-ADD')"
            >新增员工</el-button
          >
        </template>
        <!-- 右侧显示按钮 excel导入 导出 新增员工 -->
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-table border v-loading="loading" :data="list">
        <el-table-column type="index" label="序号" sortable></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          sortable
          width="120"
        ></el-table-column>
        <el-table-column width="120" label="头像" align="center">
          <!-- 插槽 -->
          <!-- <template v-slot="{row}" -->
          <template slot-scope="{ row }">
            <img
              @click="showQrCode(row.staffPhoto)"
              v-imageerror="defaultImg"
              :src="row.staffPhoto"
              style="border-radius:50%;width:100px;height:100px;padding:10px"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="workNumber"
          label="工号"
          sortable
        ></el-table-column>
        <!-- formatter用来格式化内容 -->
        <el-table-column
          prop="formOfEmployment"
          label="聘用形式"
          sortable
          :formatter="formatEmployment"
        ></el-table-column>
        <el-table-column
          prop="departmentName"
          label="部门"
          sortable
        ></el-table-column>
        <el-table-column prop="timeOfEntry" label="入职时间" sortable>
          <template slot-scope="{ row }">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="enableState" label="账户状态" sortable>
          <template slot-scope="{ row }">
            <!-- 根据当前状态判断是否打开开关 -->
            <el-switch :value="row.enableState === 1"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable width="200" fixed="right">
          <template slot-scope="{ row }">
            <el-button
              size="small"
              type="text"
              @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button
            >
            <el-button size="small" type="text">转正</el-button>
            <el-button size="small" type="text">调岗</el-button>
            <el-button size="small" type="text">离职</el-button>
            <el-button size="small" type="text" @click="editRole(row.id)"
              >角色</el-button
            >
            <el-button size="small" type="text" @click="deleteEmployee(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height:60px">
        <el-pagination
          layout="prev,pager,next"
          :page-size="page.size"
          :total="page.total"
          :current-page="page.page"
          @current-change="changePage"
        ></el-pagination>
      </el-row>
      <!-- 新增组件 -->
    </div>
    <add-demployee :show-dialog.sync="showDialog"></add-demployee>
    <!-- 分配角色的对话框 -->
    <assign-role
      ref="assignRole"
      :showRoleDialog.sync="showRoleDialog"
      :userId="userId"
    ></assign-role>
    <el-dialog title="二维码" :visible.sync="showCodeDialog" width="20%">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas"></canvas>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import AddDemployee from './components/add-employee.vue'
import EmployeeEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
import QrCode from 'qrcode'
export default {
  data() {
    return {
      defaultImg: require('@/assets/common/head.jpg'), //默认头像
      loading: false,
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      list: [],
      showDialog: false,
      showRoleDialog: false, //显示分配角色的对话框
      userId: null,
      showCodeDialog: false //显示二维码对话框
    }
  },
  components: { AddDemployee, AssignRole },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取一页数据
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    // 监听页码
    changePage(newPage) {
      this.page.page = newPage // 赋值最新页码
      this.getEmployeeList() // 重新拉取数据
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('确定删除该员工?')
        // 点击了确定
        await delEmployee(id)
        this.$message.success('删除员工成功')
        this.getEmployeeList() // 重新拉取数据
      } catch (error) {
        this.$message.error('已取消删除!')
      }
    },
    // 导出员工数据
    exportData() {
      // 导出体积较大,也不是常用功能,所以使用懒加载,按需加载
      // 表头对应关系
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        // 获取全部员工数据
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total
        })
        console.log('数据', rows)

        const data = this.formatJson(headers, rows) // 返回的data就是 要导出的结构
        console.log('表格数据', data)

        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工资料表',
          multiHeader, // 复杂表头
          merges // 合并选项
        })
      })
    },
    // 转换员工数据格式
    formatJson(headers, rows) {
      return rows.map(item => {
        // item是个对象  ,需要转为数组
        // Object.keys(headers)   数据为:['手机号', '姓名', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        // item[headers[key]]   headers[key]为英文  对应rows中item的属性名
        return Object.keys(headers).map(key => {
          // 需要判断 字段
          if (
            headers[key] === 'timeOfEntry' ||
            headers[key] === 'correctionTime'
          ) {
            // 格式化日期
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(
              obj => obj.id === item[headers[key]]
            )
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
      // return rows.map(item =>
      //   Object.keys(headers).map(key => item[headers[key]])
      // )
    },
    // 编辑角色
    async editRole(id) {
      // 弹出层
      this.userId = id // props赋值 props赋值渲染异步的
      await this.$refs.assignRole.getUserDetailById(id) // 调用子组件方法 异步方法
      this.showRoleDialog = true // 弹层
    },
    showQrCode(url) {
      // 只有url存在的情况下 才弹出对话框
      if (url) {
        // 数据更新了 但是弹层还没渲染完毕 ref对象 myCanvas还没有出现
        this.showCodeDialog = true
        // 在上一次数据更新完毕,页面渲染完毕后执行
        this.$nextTick(() => {
          // 此时已经有ref对象了
          // 如果二维码信息是个地址,会跳转到改地址,不是地址就会显示内容
          QrCode.toCanvas(this.$refs.myCanvas, url) //将url转化为二维码
        })
      } else {
        this.$message.error('该用户使用的是默认头像,还未上传头像!')
      }
    }
  }
}
</script>
<style scoped></style>
